package org.example.new_hbps_backend_reconstruction.handler;

import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.service.CalibrationService;
import org.example.new_hbps_backend_reconstruction.service.impl.CalibrationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author 丁利军
 * @date 2025年10月31日 14:38
 * @description 与心永设备端进行通信的webSocket处理器
 */

@Component
@Slf4j
public class CalibrationWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private CalibrationService calibrationService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String token = extractTokenFromSession(session);

        // 验证token
        if (!calibrationService.validateToken(token)) {
            session.close(CloseStatus.NOT_ACCEPTABLE);
            log.warn("Token验证失败，连接已关闭");
            return;
        }

        String sessionId = session.getId();
        ((CalibrationServiceImpl) calibrationService).addSession(sessionId, session);

        log.info("WebSocket连接已建立，会话ID: {}, token: {}", sessionId, token);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String sessionId = session.getId();
        String payload = message.getPayload();

        log.info("收到WebSocket消息，会话ID: {}, 消息: {}", sessionId, payload);

        // 处理WABC消息
        calibrationService.handleWABCMessage(sessionId, payload);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String sessionId = session.getId();
        ((CalibrationServiceImpl) calibrationService).removeSession(sessionId);

        log.info("WebSocket连接已关闭，会话ID: {}, 关闭状态: {}", sessionId, status);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String sessionId = session.getId();
        log.error("WebSocket传输错误，会话ID: {}", sessionId, exception);
    }

    private String extractTokenFromSession(WebSocketSession session) {
        String path = session.getUri().getPath();
        // 从路径中提取token: /api/ext/websocket/{token}
        String[] pathSegments = path.split("/");
        return pathSegments[pathSegments.length - 1];
    }
}